package classmate.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DbConnection {
	private static final String USER = "root";
	private static final String PASSWORD = "123456";
	private static final String PARAMETER8 = "characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8"; //Mysql8以上版本连接参数需设置时区
	private static final String URL = "jdbc:mysql://localhost:3306/contactsdb?"+ PARAMETER8;
	private static Connection conn;
	
	/**
	 * 获得一个数据库连接对象
	 * @return java.sql.Connection实例
	 */
	public static Connection getConnection() {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver"); //mysql8注册驱动，不建议省略
			if (conn == null) {
				conn = DriverManager.getConnection(URL, USER, PASSWORD);
			} else {
				return conn;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	public static void  close(ResultSet rs,PreparedStatement ps) {
		try {
			if(rs !=null) {
				rs.close();// 关闭结果集
				rs = null;
			}
			if(ps !=null) {
				ps.close(); // 关闭预处理
				ps = null;
			}
		    if(conn !=null) {
		        conn.close(); // 关闭连接
		        conn = null;
		    }
		    
	    } catch (SQLException e) {
			e.printStackTrace();
		} 
	}
}
